package com.bw.z.mvp.view.news;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.blankj.utilcode.util.LogUtils;
import com.bw.z.App;
import com.bw.z.R;
import com.bw.z.db.DBManager;
import com.bw.z.db.UserTable;
import com.bw.z.mvp.HttpCode;
import com.bw.z.mvp.base.view.BaseActivity;
import com.bw.z.mvp.contract.NewsContract;
import com.bw.z.mvp.di.DaggerNewsComponent;
import com.bw.z.mvp.di.NewsModules;
import com.bw.z.mvp.model.entity.BaseEntity;
import com.bw.z.mvp.model.entity.CommentEntity;
import com.bw.z.mvp.presenter.NewsPresenter;
import com.bw.z.mvp.view.news.adapter.CommentAdapter;
import com.bw.z.utils.GlideUtils;
import com.bw.z.utils.SpUtils;
import com.bw.z.utils.ToastUtils;
import com.google.android.material.appbar.AppBarLayout;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.tb.emoji.Emoji;
import com.tb.emoji.EmojiUtil;
import com.tb.emoji.FaceFragment;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NewsValuesActivity extends BaseActivity<NewsPresenter>
        implements NewsContract.NewView, View.OnClickListener, FaceFragment.OnEmojiClickListener,
        AppBarLayout.OnOffsetChangedListener, OnRefreshLoadMoreListener {

    //TODO 第三周作业
    /**
     * 1.点击首页新闻列表跳转到WebValuesActivity使用x5浏览器加载网页url
     * 2.新闻资讯详情界面收藏功能实现;
     * 3.人民号fragment下点击列表中item，跳转到首页的新闻详情界面，传递url以及news_id 复用首页新闻资讯详情界面;
     * 4.直播详情界面编写完成;
     * 5.首页新闻详情页编写完成接入百度地图LBS SDK->发表评论时的address 参数使用当前所在城市;
     * 6.人民号中作者用户详情界面;
     * 7.退出登录界面;
     * 8.更新逻辑编写;
     * 9.视频全屏播放界面;
     * 视频直播详情界面编写: GSY播放器框架的集成以及使用: GSY播放器基于IJKPlayer EXO 播放器框架集成， 整合提供了播放器播放逻辑以及播放界面； 视频播放，音频播放，直播拉流; IJKPalyer:软解->mp4,mp3,m3u8,rtmp,rtsp,flv(flish视频格式) EXO->google官方提供->硬解->GPU->不同厂商兼容问题
     */

    private android.widget.RelativeLayout webValuesTop;
    private android.widget.ImageView headBackImg;
    private android.widget.RelativeLayout webValuesBottomRelative;
    private android.widget.ImageView liveShareImg;
    private android.widget.ImageView liveCollectionImg;
    private android.widget.RelativeLayout liveMsgRelative;
    private android.widget.RelativeLayout liveEdtBtn;//开启输入框
    private android.widget.ImageView liveFaceImg;//显示表情包
    private View webValuesLine;
    private AppBarLayout webValuesAppbar;
    private LinearLayoutManager manager;
    private com.bw.z.widget.x5.X5WebView webValuesX5;
    private androidx.recyclerview.widget.RecyclerView webValuesCommentRv;
    private android.widget.RelativeLayout liveBottomView;//输入系统整体布局
    private android.widget.EditText liveMsgEdt;
    private android.widget.TextView liveSendTv;//发送按钮
    private android.widget.ImageView liveVoiceImg;
    private android.widget.ImageView liveEmojiImg;//输入系统显示表情
    private android.widget.LinearLayout liveEmojiLinear;//表情系统布局
    private View headView;
    private CommentAdapter commentAdapter;
    private long news_id = 0;
    private String news_url;
    //当前界面中appbarLayout展开以及折叠标志,false折叠true展开
    private boolean appFlag = true;
    private android.widget.TextView liveMsgNumTv;
    private List<CommentEntity.Values> list = new ArrayList<>();
    private com.scwang.smart.refresh.layout.SmartRefreshLayout webValuesSmart;
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private boolean collectFlag = false;

    @Override
    public View addStatusView() {
        return f(R.id.new_values_root);
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取地址相关的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            String city = location.getCity();    //获取城市
            UserTable load = new DBManager(NewsValuesActivity.this).getDaoSession().getUserTableDao().load(SpUtils.readDataLong("user_id"));
            Map<String, Object> map = new HashMap<>();
            map.put("code", HttpCode.ADDCOMMENTCODE);
            map.put("comment_address", city + "");
            map.put("comment_time", System.currentTimeMillis() / 1000);
            map.put("comment_value", liveMsgEdt.getText().toString());
            map.put("news_id", news_id);
            map.put("user_id", load.getUser_id());
            //发布评论
            p.requestAll(map);
        }
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_news_values;
    }

    @Override
    public void initView() {
        getColors(Color.WHITE);
        headView = LayoutInflater.from(this).inflate(R.layout.view_web_values, null);
        news_url = getIntent().getExtras().getString("news_url");
        news_id = getIntent().getExtras().getLong("news_id", 0);

        webValuesTop = findViewById(R.id.web_values_top);
        headBackImg = findViewById(R.id.head_back_img);
        webValuesBottomRelative = findViewById(R.id.web_values_bottom_relative);
        liveShareImg = findViewById(R.id.live_share_img);
        liveCollectionImg = findViewById(R.id.live_collection_img);
        liveMsgRelative = findViewById(R.id.live_msg_relative);
        liveEdtBtn = findViewById(R.id.live_edt_btn);
        liveFaceImg = findViewById(R.id.live_face_img);
        webValuesLine = findViewById(R.id.web_values_line);
        webValuesX5 = findViewById(R.id.web_values_x5);
        webValuesCommentRv = findViewById(R.id.web_values_comment_rv);
        liveBottomView = findViewById(R.id.live_bottom_view);
        liveMsgEdt = findViewById(R.id.live_msg_edt);
        liveSendTv = findViewById(R.id.live_send_tv);
        liveVoiceImg = findViewById(R.id.live_voice_img);
        liveEmojiImg = findViewById(R.id.live_emoji_img);
        liveEmojiLinear = findViewById(R.id.live_emoji_linear);
        liveMsgNumTv = findViewById(R.id.live_msg_num_tv);
        webValuesAppbar = findViewById(R.id.web_values_appbar);
        webValuesSmart = findViewById(R.id.web_values_smart);

        webValuesSmart.setEnableLoadMore(true);
        webValuesSmart.setEnableRefresh(true);
        webValuesSmart.setRefreshHeader(new ClassicsHeader(this));
        webValuesSmart.setRefreshFooter(new ClassicsFooter(this));
        webValuesSmart.setOnRefreshLoadMoreListener(this);

        webValuesX5.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                if (!s.contentEquals("http://118.195.161.134:8066/"))
                    return true;
                return false;
            }
        });

        getSupportFragmentManager().beginTransaction()
                .add(R.id.live_emoji_linear, FaceFragment.Instance())
                .commit();
        webValuesX5.loadUrl(news_url);
        manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        webValuesCommentRv.setLayoutManager(manager);
        commentAdapter = new CommentAdapter();
        commentAdapter.setEmptyView(R.layout.view_empty);
        commentAdapter.addHeaderView(headView);
        webValuesCommentRv.setAdapter(commentAdapter);
        liveEdtBtn.setOnClickListener(this::onClick);
        liveFaceImg.setOnClickListener(this::onClick);
        liveEmojiImg.setOnClickListener(this::onClick);
        liveSendTv.setOnClickListener(this::onClick);
        headBackImg.setOnClickListener(this::onClick);
        liveMsgRelative.setOnClickListener(this::onClick);
        liveCollectionImg.setOnClickListener(this::onClick);
        webValuesAppbar.addOnOffsetChangedListener(this);

        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);
        //可选，是否需要地址信息，默认为不需要，即参数为false
        //如果开发者需要获得当前点的地址信息，此处必须为true
        option.setNeedNewVersionRgc(true);
        option.setAddrType("all");
//        option.setScanSpan(5000);
        //可选，设置是否需要最新版本的地址信息。默认需要，即参数为true
        mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.live_edt_btn:
                liveBottomView.setVisibility(View.VISIBLE);
                liveEmojiLinear.setVisibility(View.GONE);
                break;
            case R.id.live_emoji_img:
                if (liveEmojiLinear.getVisibility() == View.VISIBLE) {
                    //当前正在显示表情系统->隐藏掉表情布局
                    liveEmojiLinear.setVisibility(View.GONE);
                    liveEmojiImg.setImageResource(R.mipmap.res_7icon_129);
                } else {
                    //当前正在隐藏表情系统->显示表情布局
                    liveEmojiLinear.setVisibility(View.VISIBLE);
                    liveEmojiImg.setImageResource(R.mipmap.res_7icon_131);
                }
                break;
            case R.id.live_send_tv:
                if (liveMsgEdt.getText() == null) {
                    ToastUtils.showMsg("请输入评论内容");
                    return;
                }
                if (liveMsgEdt.getText().toString().isEmpty()) {
                    ToastUtils.showMsg("请输入评论内容");
                    return;
                }
                //开启定位
                mLocationClient.start();
                break;
            case R.id.live_face_img:
                liveBottomView.setVisibility(View.VISIBLE);
                liveEmojiLinear.setVisibility(View.VISIBLE);
                break;
            case R.id.live_msg_relative:
                appFlag = !appFlag;
                webValuesAppbar.setExpanded(appFlag);
                break;
            case R.id.head_back_img:
                finish();
                break;
            case R.id.live_collection_img:
                collectFlag = !collectFlag;
                Map<String, Object> map = new HashMap<>();
                // 收藏
                if (collectFlag) {
                    // 添加收藏
                    map.put("code", HttpCode.ADDCOLLECTIONCODE);
                } else {
                    // 取消收藏
                    map.put("code", HttpCode.DELCOLLECTIONCODE);
                }
                map.put("news_id", news_id);
                int user_id = App.getInstance().getDaoSession().getUserTableDao().load(SpUtils.readDataLong("user_id")).getUser_id();
                map.put("user_id", user_id);
                p.requestAll(map);
                break;
        }
    }

    @Override
    public void inject() {
        DaggerNewsComponent.builder().newsModules(new NewsModules(this)).build().injectWebValuesNews(this);
    }

    @Override
    public void initData() {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpCode.SELCOMMENTCODE);
        map.put("news_id", news_id);

        // 请求是否收藏
        Map<String, Object> collectMap = new HashMap<>();
        collectMap.put("code", HttpCode.ISCOLLECTIONCODE);
        collectMap.put("news_id", news_id);
        int user_id = App.getInstance().getDaoSession().getUserTableDao().load(SpUtils.readDataLong("user_id")).getUser_id();
        collectMap.put("user_id", user_id);

        p.requestAll(map, collectMap);
        com.bw.z.utils.LogUtils.show("请求获取最新评论列表");

    }

    @Override
    public void refreshAll(BaseEntity baseEntity) {
        LogUtils.json(baseEntity);
        if (baseEntity instanceof CommentEntity) {
            CommentEntity commentEntity = (CommentEntity) baseEntity;
            commentAdapter.setNewInstance(commentEntity.getValues());
        } else {
            if (baseEntity.message.equals("发表成功")) {
                ToastUtils.showMsg("发表成功");
                //当前评论发布成功
                //清空输入框
                liveMsgEdt.setText("");
                //隐藏输入框
                liveBottomView.setVisibility(View.GONE);
                //刷新评论列表数据
                //请求获取最新评论列表
//                initData();
            } else if (baseEntity.message.equals("失败")) {
                GlideUtils.getInstance().GlideImageUrl(R.mipmap.res_7icon_149, liveCollectionImg);
                collectFlag = false;
            } else if (baseEntity.message.equals("收藏成功")) {
                GlideUtils.getInstance().GlideImageUrl(R.mipmap.res_7icon_139, liveCollectionImg);
                collectFlag = true;
            } else if (baseEntity.message.equals("取消收藏成功")) {
                GlideUtils.getInstance().GlideImageUrl(R.mipmap.res_7icon_149, liveCollectionImg);
                collectFlag = false;
            } else {
                GlideUtils.getInstance().GlideImageUrl(R.mipmap.res_7icon_139, liveCollectionImg);
                collectFlag = true;
            }
        }
    }

    @Override
    public void refreshRecyclerView(BaseEntity baseEntity) {
        CommentEntity commentEntity = (CommentEntity) baseEntity;
        if (commentEntity.getValues() == null) {
            ToastUtils.showMsg("请求出错");
            return;
        }
        commentAdapter.setNewInstance(commentEntity.getValues());
    }

    @Override
    public void loadMoreRecyclerView(BaseEntity baseEntity) {
        CommentEntity commentEntity = (CommentEntity) baseEntity;
        if (commentEntity.getValues() == null) {
            ToastUtils.showMsg("最后一页");
            return;
        }
        commentAdapter.addData(commentEntity.getValues());
    }

    @Override
    public void onEmojiDelete() {
        String text = liveMsgEdt.getText().toString();
        if (text.isEmpty()) {
            return;
        }
        if ("]".equals(text.substring(text.length() - 1, text.length()))) {
            int index = text.lastIndexOf("[");
            if (index == -1) {
                int action = KeyEvent.ACTION_DOWN;
                int code = KeyEvent.KEYCODE_DEL;
                KeyEvent event = new KeyEvent(action, code);
                liveMsgEdt.onKeyDown(KeyEvent.KEYCODE_DEL, event);
                try {
                    EmojiUtil.handlerEmojiText(liveMsgEdt, liveMsgEdt.getText().toString(), this);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return;
            }
            liveMsgEdt.getText().delete(index, text.length());
            try {
                EmojiUtil.handlerEmojiText(liveMsgEdt, liveMsgEdt.getText().toString(), this);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        int action = KeyEvent.ACTION_DOWN;
        int code = KeyEvent.KEYCODE_DEL;
        KeyEvent event = new KeyEvent(action, code);
        liveMsgEdt.onKeyDown(KeyEvent.KEYCODE_DEL, event);
        try {
            EmojiUtil.handlerEmojiText(liveMsgEdt, liveMsgEdt.getText().toString(), this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (liveBottomView.getVisibility() == View.VISIBLE) {
                liveBottomView.setVisibility(View.GONE);
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onEmojiClick(Emoji emoji) {
        if (emoji != null) {
            int index = liveMsgEdt.getSelectionStart();
            Editable editable = liveMsgEdt.getEditableText();
            if (index < 0) {
                editable.append(emoji.getContent());
            } else {
                editable.insert(index, emoji.getContent());
            }
            try {
                EmojiUtil.handlerEmojiText(liveMsgEdt, liveMsgEdt.getText().toString(), this);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private int oldverticalOffset;

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        if (oldverticalOffset == verticalOffset)
            return;
        if (verticalOffset == 0) {
            //当前显示正文
            appFlag = true;
            liveMsgNumTv.setText("99+");
        } else {
            appFlag = false;
            liveMsgNumTv.setText("正文");
        }
        oldverticalOffset = verticalOffset;
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        refreshLayout.finishLoadMore();
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpCode.SELCOMMENTCODE);
        map.put("news_id", news_id);
        p.requestLoad(map);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        list.clear();
        refreshLayout.finishRefresh();
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpCode.SELCOMMENTCODE);
        map.put("news_id", news_id);
        p.requestRefresh(map);
    }
}